package com.share.admin.config.security;

import com.share.admin.model.db.User;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 用户信息
 * <p>
 * 来自UserDetails实现的方法返回值必须配置为true,否则后面无法访问
 *
 * @author ruoyi
 */
@Data
public class LoginUser implements UserDetails {
    private User user;
    private Set<String> permissions;

    public LoginUser(User user, Set<String> permissions) {
        this.user = user;

        if (permissions == null) {
            this.permissions = new HashSet<>();
        } else {
            this.permissions = permissions;
        }
    }


    // @PreAuthorize("hasAuthority('system:user:query')")这个注解后面会和getAuthorities关联对比
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> reSet = new HashSet<>();
        //注意---redis 无法序列化GrantedAuthority,所以每取一次都要遍历
        for (String perm : permissions) {
            reSet.add(new SimpleGrantedAuthority(perm));
        }
        return reSet; //该用户有哪些权限
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getAccount();
    }

    //账号过期状态（true账号没有过期，false账号已过期）
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    //账号没有锁住状态（true账号没有锁住，false账号锁住）
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    //凭证过期状态（true账号未过期，false已过期）
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    //账号启用状态（true账号未过期，false账号已过期）
    @Override
    public boolean isEnabled() {
        return true;
    }
}
